package de.homelabs.hlmodules.cms.template.service;

import java.io.IOException;
import java.io.Reader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import de.homelabs.hlmodules.cms.template.domain.HLTemplate;
import de.homelabs.hlmodules.cms.template.domain.HLTemplateException;
import freemarker.cache.TemplateLoader;

/**
 * Wrapper to use HLTemplateManager as FreemarkerTemplateLoader. The first class
 * called by the freemarker framework to interact with the template. Calls a
 * IHLTemplateManager implementation to call a strategy for that.
 * 
 * @author D.Mueller
 * 
 */
@Component("hlTemplateLoaderWrapper")
public class HLTemplateLoaderWrapper implements TemplateLoader {

	@Autowired
	@Qualifier("hlFreeMarkerTemplateManager")
	private HLFreemarkerTemplateManager templateManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see freemarker.cache.TemplateLoader#findTemplateSource(java.lang.String)
	 */
	public Object findTemplateSource(String name) throws IOException {
		try {
			return templateManager.findTemplateSource(name);
		} catch (HLTemplateException e) {
			//Freemarker does not know about HLTemplateException
			throw new IOException(e.toFullErrorText());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see freemarker.cache.TemplateLoader#getLastModified(java.lang.Object)
	 */
	public long getLastModified(Object templateSource) {
		try {
			return templateManager.getLastModified((HLTemplate) templateSource);
		} catch (HLTemplateException e) {
			//Freemarker does not know about HLTemplateException 
			//nor IOExcpetion (Why not??), hack
			return 0L;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see freemarker.cache.TemplateLoader#getReader(java.lang.Object,
	 * java.lang.String)
	 */
	public Reader getReader(Object templateSource, String encoding)
			throws IOException {
		try {
			return templateManager.getReader((HLTemplate) templateSource, encoding);
		} catch (HLTemplateException e) {
			//Freemarker does not know about HLTemplateException
			throw new IOException(e.toFullErrorText());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * freemarker.cache.TemplateLoader#closeTemplateSource(java.lang.Object)
	 */
	public void closeTemplateSource(Object templateSource) throws IOException {
		try {
			templateManager.closeTemplateSource((HLTemplate) templateSource);
		} catch (HLTemplateException e) {
			//Freemarker does not know about HLTemplateException
			throw new IOException(e.toFullErrorText());
		}
	}

}
